import React, { useEffect, useState, useCallback } from 'react';
import {
  RefreshCw,
  Users,
  Video,
  CreditCard,
  Clock,
  CheckCircle,
  XCircle,
  Loader,
  Activity,
  Database,
} from 'lucide-react';
import { dashboardApi } from '../api';
import type { DashboardStats } from '../api/types';
import { useApiError } from '../hooks/useApiError';

interface MetricCardProps {
  title: string;
  value: number;
  icon: React.ElementType;
  color: string;
  subtitle?: string;
}

const MetricCard: React.FC<MetricCardProps> = ({ title, value, icon: Icon, color, subtitle }) => (
  <div className="bg-gray-900 border border-gray-800 rounded-xl p-6 hover:border-gray-700 transition-colors">
    <div className="flex items-center justify-between">
      <div className="flex-1">
        <p className="text-sm text-gray-400 mb-1">{title}</p>
        <p className="text-3xl font-bold text-gray-100">{value.toLocaleString()}</p>
        {subtitle && <p className="text-xs text-gray-500 mt-1">{subtitle}</p>}
      </div>
      <div className={`p-3 rounded-lg ${color}`}>
        <Icon className="w-6 h-6 text-white" />
      </div>
    </div>
  </div>
);

interface StatRowProps {
  label: string;
  value: number;
  icon: React.ElementType;
  color: string;
}

const StatRow: React.FC<StatRowProps> = ({ label, value, icon: Icon, color }) => (
  <div className="flex items-center justify-between py-3 border-b border-gray-800 last:border-b-0">
    <div className="flex items-center space-x-3">
      <Icon className={`w-5 h-5 ${color}`} />
      <span className="text-gray-300">{label}</span>
    </div>
    <span className="text-gray-100 font-semibold">{value.toLocaleString()}</span>
  </div>
);

const Dashboard: React.FC = () => {
  const { handleError } = useApiError();
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [lastUpdated, setLastUpdated] = useState<Date>(new Date());

  const loadDashboardData = useCallback(async () => {
    try {
      const data = await dashboardApi.getStats();
      setStats(data);
      setLastUpdated(new Date());
    } catch (error) {
      handleError(error, '加载仪表盘数据失败');
    } finally {
      setLoading(false);
    }
  }, [handleError]);

  useEffect(() => {
    loadDashboardData();
    // 每30秒刷新一次数据
    const interval = setInterval(loadDashboardData, 30000);
    return () => clearInterval(interval);
  }, [loadDashboardData]);

  const refreshData = useCallback(async () => {
    setLoading(true);
    await loadDashboardData();
  }, [loadDashboardData]);

  if (loading && !stats) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <Loader className="w-8 h-8 animate-spin text-cyan-500 mx-auto mb-2" />
          <p className="text-gray-400">正在加载仪表盘数据...</p>
        </div>
      </div>
    );
  }

  if (!stats) {
    return (
      <div className="text-center py-12">
        <XCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
        <p className="text-xl text-gray-300 mb-2">无法加载仪表盘数据</p>
        <button
          onClick={refreshData}
          className="px-4 py-2 bg-cyan-600 hover:bg-cyan-700 text-white rounded-lg transition-colors cursor-pointer"
        >
          重新加载
        </button>
      </div>
    );
  }

  const videoSuccessRate =
    stats.videos.total > 0
      ? ((stats.videos.completed / stats.videos.total) * 100).toFixed(1)
      : '0.0';

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold text-gray-100 mb-2">管理仪表盘</h2>
          <p className="text-gray-400">实时监控您的AI视频生成平台运行状态</p>
        </div>
        <div className="flex items-center space-x-4">
          <div className="text-right">
            <p className="text-sm text-gray-400">最后更新</p>
            <p className="text-sm text-gray-300">{lastUpdated.toLocaleTimeString()}</p>
          </div>
          <button
            onClick={refreshData}
            disabled={loading}
            className="p-2 bg-gray-800 hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50 cursor-pointer disabled:cursor-not-allowed"
            title="刷新数据"
          >
            <RefreshCw className={`w-5 h-5 text-gray-400 ${loading ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </div>

      {/* Main Metrics Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <MetricCard
          title="AI服务账户"
          value={stats.accounts.active}
          icon={CreditCard}
          color="bg-gradient-to-br from-blue-500 to-blue-600"
          subtitle={`共 ${stats.accounts.total} 个账户`}
        />
        <MetricCard
          title="Avatar组"
          value={stats.avatars.groups}
          icon={Users}
          color="bg-gradient-to-br from-purple-500 to-purple-600"
          subtitle={`${stats.avatars.total} 个Avatar`}
        />
        <MetricCard
          title="视频总数"
          value={stats.videos.total}
          icon={Video}
          color="bg-gradient-to-br from-cyan-500 to-cyan-600"
          subtitle={`成功率 ${videoSuccessRate}%`}
        />
        <MetricCard
          title="处理中"
          value={stats.videos.processing}
          icon={Activity}
          color="bg-gradient-to-br from-orange-500 to-orange-600"
          subtitle={stats.videos.processing > 0 ? '正在处理' : '无任务'}
        />
      </div>

      {/* Detailed Stats */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Video Statistics */}
        <div className="bg-gray-900 border border-gray-800 rounded-xl p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-xl font-semibold text-gray-100 flex items-center">
              <Video className="w-5 h-5 text-cyan-500 mr-2" />
              视频统计
            </h3>
          </div>
          <div className="space-y-1">
            <StatRow
              label="已完成"
              value={stats.videos.completed}
              icon={CheckCircle}
              color="text-green-400"
            />
            <StatRow
              label="处理中"
              value={stats.videos.processing}
              icon={Clock}
              color="text-blue-400"
            />
            <StatRow label="失败" value={stats.videos.failed} icon={XCircle} color="text-red-400" />
            <StatRow
              label="草稿"
              value={stats.videos.draft}
              icon={Database}
              color="text-gray-400"
            />
          </div>
        </div>

        {/* System Status */}
        <div className="bg-gray-900 border border-gray-800 rounded-xl p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-xl font-semibold text-gray-100 flex items-center">
              <Database className="w-5 h-5 text-cyan-500 mr-2" />
              系统状态
            </h3>
          </div>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <span className="text-gray-400">AI服务状态</span>
              <div className="flex items-center space-x-2">
                <div className="w-2 h-2 bg-green-400 rounded-full"></div>
                <span className="text-green-400 text-sm">正常</span>
              </div>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-gray-400">活跃账户</span>
              <span
                className={`text-sm ${stats.accounts.active > 0 ? 'text-green-400' : 'text-red-400'}`}
              >
                {stats.accounts.active > 0 ? `${stats.accounts.active} 个` : '无'}
              </span>
            </div>
            {stats.system.last_sync_at && (
              <div className="flex items-center justify-between">
                <span className="text-gray-400">最后同步</span>
                <span className="text-gray-300 text-sm">
                  {new Date(stats.system.last_sync_at).toLocaleString('zh-CN')}
                </span>
              </div>
            )}
            <div className="flex items-center justify-between">
              <span className="text-gray-400">数据统计</span>
              <span className="text-gray-300 text-sm">实时更新</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
